import typing
import logging
from threading import RLock

from tinyops.library.json_helper import shorten_text
from .interface import INotifier

LOG = logging.getLogger(__name__)


class UnionNotifier(INotifier):
    def __init__(self, notifiers: typing.List[INotifier]):
        self.name = 'UnionNotifier'
        self.notifiers = notifiers or []
        self.lock = RLock()

    def notify(self, title, content=None):
        LOG.info(f'notify notifiers={len(self.notifiers)} title={title!r} '
                 f'content={shorten_text(content, 40)!r}')
        with self.lock:
            for n in self.notifiers:
                try:
                    n.notify(title, content=content)
                except Exception as ex:
                    LOG.error(f"notify {n.name} failed", exc_info=ex)

    def close(self):
        with self.lock:
            for n in self.notifiers:
                n.close()
